﻿#region -- 版 本 注 释 --
/****************************************************
* 文 件 名：
* Copyright(c) 王树羽
* CLR 版本: 4.5
* 创 建 人：王树羽
* 电子邮箱：674613047@qq.com
* 官方网站：https://www.cnblogs.com/shuyu
* 创建日期：2019-05-09
* 文件描述：
******************************************************
* 修 改 人：
* 修改日期：
* 备注描述：
*******************************************************/
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CommonLib
{
    /// <summary>
    /// 文件帮助类
    /// </summary>
    public class FileHelper
    {
        #region 文件读写

        /// <summary>
        /// 文件写入锁
        /// </summary>
        protected static object FileLock = new object();

        /// <summary>
        /// 文件写入方法
        /// </summary>
        /// <param name="path">文件路径:绝对路径</param>
        /// <param name="str">写入内容</param>
        /// <param name="append">是否追加</param>
        /// <param name="encoding">编码格式</param>
        public static void FileWrite(string path, string str, bool append = false, string encoding = "utf-8")
        {
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            System.Text.Encoding code = System.Text.Encoding.GetEncoding(encoding);
            System.IO.StreamWriter sw = null;
            try
            {
                lock (FileLock)
                {
                    sw = new System.IO.StreamWriter(path, append, code);
                    sw.Write(str);
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 文件读取方法
        /// </summary>
        /// <param name="path">文件路径:绝对路径</param>
        /// <param name="encoding">编码格式</param>
        public static string FileRead(string path, string encoding = "utf-8")
        {
            //源码是替换掉模板中的特征字符 
            Encoding code = Encoding.GetEncoding(encoding);
            System.IO.StreamReader Sr = null;

            string str = "";

            //读取
            try
            {
                Sr = new StreamReader(path, code);
                str = Sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Sr.Close();
            }
            return str;
        }

        #endregion 文件读写

        #region 文件拷贝

        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="sourceFileName">原始文件</param>
        /// <param name="destFileName">目标地址</param>
        /// <param name="overwrite">是否覆盖</param>
        public static string FileCopy(string sourceFileName, string destFileName, bool overwrite = true)
        {
            var result = "";
            if (File.Exists(sourceFileName))
            {
                var dir = Path.GetDirectoryName(destFileName);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                File.Copy(sourceFileName, destFileName, overwrite);
            }
            else
            {
                result = "原始文件不存在";
            }
            return result;
        }

        #endregion


        #region 文件流操作

        /// <summary>
        /// 读取文件为 byte[]
        /// </summary>
        /// <param name="path">文件路径:绝对路径</param>
        public static byte[] FileToBytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];

            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            return buff;
        }

        /// <summary>
        /// byte[] 保存为 文件
        /// </summary>
        /// <param name="bytes">二进制流</param>
        /// <param name="saveFile">文件路径:绝对路径</param>
        public static void BytesToFile(byte[] bytes, string saveFile)
        {
            if (System.IO.File.Exists(saveFile))
            {
                System.IO.File.Delete(saveFile);
            }
            var dir = Path.GetDirectoryName(saveFile);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            FileStream fs = new FileStream(saveFile, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes, 0, bytes.Length);
            bw.Close();
            fs.Close();
        }

        #endregion 文件读写


        #region 获取目录下所有文件

        /// <summary>
        ///获取目录下所有文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="searchPattern"></param>
        /// <returns></returns>

        public static List<string> GetFiles(string path, string searchPattern = "*.*")
        {
            var list = new List<string>();
            if (Directory.Exists(path))
            {
                list = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories).ToList();
            }
            return list;
        }
        #endregion

        #region 返回以当天日期命名的文件夹

        /// <summary>
        /// 返回以当天日期命名的文件夹
        /// </summary>
        /// <param name="Root">根目录，不定义则用默认的 /upload</param>
        /// <returns></returns>
        public static string SavedFolder(string Root = "")
        {
            string path = "/upload/" + DateTime.Today.ToString("yyyy-MM-dd") + "/";
            if (Root != "")
            {
                path = Root + DateTime.Today.ToString("yyyy-MM-dd") + "/";
            }
            var _path = System.AppDomain.CurrentDomain.BaseDirectory + path;
            if (!System.IO.Directory.Exists(_path))
            {
                System.IO.Directory.CreateDirectory(_path);
            }
            return path;
        }

        #endregion 返回以当天日期命名的文件夹
    }
}
